package com.qt.myboot.shiro;

import com.qt.myboot.controller.LoginController;
import com.qt.myboot.dao.RolePermissionsRepository;
import com.qt.myboot.dao.UserRoleRelationRepository;
import com.qt.myboot.entity.User;
import com.qt.myboot.enums.UserErrorCodeEnum;
import com.qt.myboot.exception.UserErrorCodeException;
import com.qt.myboot.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.InvalidSessionException;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;

import java.util.List;


@Slf4j
public class ShiroRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;
    @Autowired
    private UserRoleRelationRepository userRoleRelationRepository;
    @Autowired
    private RolePermissionsRepository rolePermissionsRepository;

    /**
     * @Description:
     * @Author: xusl
     * @Date: 2019/5/31 15:52
     * @Param: [principalCollection]
     * @return: org.apache.shiro.authz.AuthorizationInfo
     **/
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        log.info("认证。。。权限 =======> {}", principalCollection.toString());

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        try {
            List<String> roles = (List<String>) session.getAttribute("roles");
            List<String> permissions = (List<String>) session.getAttribute("permissions");
            info.addRoles(roles);
            info.addStringPermissions(permissions);
        } catch (InvalidSessionException e) {
            throw new UserErrorCodeException(UserErrorCodeEnum.US46);
        }
        //设置登录次数、时间
//        userService.updateUserLogin(user);
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        log.info("doGetAuthenticationInfo: ------> {}", authenticationToken.toString());

        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String userName = token.getUsername();
        log.info(userName + token.getPassword());

        User user = userService.findByName(User.builder().userName(token.getUsername()).build());
        if (user != null) {
//            byte[] salt = Encodes.decodeHex(user.getSalt());
//            ShiroUser shiroUser=new ShiroUser(user.getId(), user.getLoginName(), user.getName());
            //设置用户session
            Session session = SecurityUtils.getSubject().getSession();

            List<String> roles = userRoleRelationRepository.findRoleByUserId(user.getId());
            session.setAttribute("roles", roles);

            List<Integer> roleIds = userRoleRelationRepository.findRoleIdByUserId(user.getId());
            List<String> permissions = null;
            if (!CollectionUtils.isEmpty(roleIds)) {
                 permissions = rolePermissionsRepository.findPermissionsNameByRoleIdIn(roleIds);
            }
            if (!CollectionUtils.isEmpty(permissions)) {
                session.setAttribute("permissions", permissions);
                log.info("roles = {}", roles);
                log.info("permissions = {}", permissions);
            }

            return new SimpleAuthenticationInfo(userName, user.getPassword(), getName());
        } else {
            return null;
        }

    }

}
